<template>
	<view class="page">
		<view class="hecswap" :initdata="initdata" :change:initdata="ether.getalldata" :approvestatus="approvestatus"
			:change:approvestatus="ether.approve" :implementid="implementid" :change:implementid="ether.implement">
			<view class="block1">
				<view class="line5">
					<view class="left">
						<image class="image"
							src="../../static/images/tokenicon/0x0000000000000000000000000000000000000000ETH5867.png"
							mode="widthFix"></image>
						<view class="text">JumpFinance</view>
					</view>
					<view class="center">
						<image class="image" src="../../static/images/kualian.png" mode="widthFix"></image>
					</view>
					<view class="right" @tap="openselectchain">
						<image class="image" v-if="chainname=='请选择'" src="../../static/images/notoken.png"
							mode="widthFix"></image>
						<image class="image" v-if="chainname!='请选择'"
							:src="'../../static/images/chain/'+chainname+'.png'" mode="widthFix"></image>
						<view class="text">{{chainname}}</view>
					</view>
				</view>
				<view class="line4">
					<view class="left">余额：{{ Number(Number(usernum).toFixed(4)) }}</view>
					<view class="right">
						<view class="text" @tap="ether.getusernum">
							刷新
						</view>
					</view>
				</view>
				<view class="line2">
					<view class="left">
						<image class="tokenicon"
							src="@/static/images/tokenicon/0x55d398326f99059fF775485246999027B3197955ETH56.png"
							mode="widthFix"></image>
						<view class="texts">
							<view class="text1">
								USDT
							</view>
							<view class="text2">
								JumpFinance
							</view>
						</view>
					</view>
					<view class="right">
						<uni-easyinput class="numinput" type='number' v-model="num" placeholder="请输入跨链数量" />
					</view>
				</view>
				<view class="toaddress">
					<uni-easyinput class="toaddressinput" type="text" :styles="inputstyles" v-model="toaddress"
						placeholder="请输入接收地址" />
				</view>
				<view class="line6">
					<view class="button button1" :data-usernum="usernum" :data-num="num" :data-toaddress="toaddress"
						:data-chainname="chainname" :data-min="min" @tap="ether.cross">
						跨链
					</view>
				</view>
			</view>
			<view class="block2">
				<view class="line">
					<view class="left">最小跨链数量</view>
					<view class="right">{{min}}</view>
				</view>
				<view class="line">
					<view class="left">手续费</view>
					<view class="right">{{fee}}</view>
				</view>
			</view>
			<view class="logBox" v-if="log.length>0">
				<view class="title">
					<text>最近一条记录</text>
					<text class="more" @tap="logPage">更多记录</text>
				</view>
				<clog :data="log[0]"></clog>
			</view>
		</view>
	</view>
</template>
<script>
	import {
		getcrossinfo
	} from "@/http/api.js"
	import common from '@/js_sdk/common/common.js'
	export default {
		props: {
			log: {
				type: Array,
				default: []
			},
		},
		data() {
			return {
				...common.config,
				// 选中链的名称
				chainname: "请选择",
				// 用户要兑换的代币余额
				usernum: 0,
				// 用户要兑换的代币数量
				num: "",
				// 要兑换到的地址
				toaddress: "",
				// 预授权执行状态
				approvestatus: false,
				// 执行合约的ID
				implementid: "",
				// 输入框的样式
				inputstyles: {
					height: "100px"
				},
				// 跨链手续费
				fee: "请选择链",
				// 最小跨链数量
				min: "请选择链"
			}
		},
		computed: {
			// 同步给rendjs层的数据
			initdata() {
				return {
					addressInfo: this.$store.getters.addressInfo,
					selectedRpc: this.$store.getters.getRpc,
					config: common.config,
				}
			},
		},
		watch: {
			chainname(value) {
				if (value == "TRON") {
					this.getcrossinfo("0", this.jumpusdt)
				} else if (value == "BSC") {
					this.getcrossinfo("56", this.jumpusdt)
				}
			}
		},
		methods: {
			...common.methonds,
			//添加跨链记录
			addCrossLog(hash){
				this.$emit("addCrossLog", hash)
			},
			getcrossinfo(chain, address) {
				let params = {
					chain: chain,
					address: address
				}
				getcrossinfo(params).then(res => {
					if (res.code == 200) {
						this.min = res.data.min
						this.fee = res.data.fee
					}
				})
			},
			logPage() {
				uni.navigateTo({
					url: `/pages/logPage/logPage`
				})
			},
			// 打开选择主链弹窗
			openselectchain() {
				this.$emit("openselectchain")
			},
			// 获取用户要兑换的代币余额
			getusernum2(data) {
				this.usernum = data
			},
			// 打开授权弹窗
			approveopen() {
				let data = {
					type: "JUMPCROSS",
					token: "USDT",
					tip: "使用跨链功能需要对代币进行授权，授权成功后请重新操作。"
				}
				this.$emit("approveopen", data);
			},
			// 打开底部确认弹窗
			openimplement(data) {
				// 这个变量修改是为了让授权执行状态结束，不影响其他，所以就这样写了
				let info = {
					type: "JUMPCROSS",
					data: data
				}
				this.$emit("executionopen", info)
			},
			// 修改预授权状态
			changeapprovestatus(status) {
				this.approvestatus = status
			},
			// 执行结束
			implementover() {
				this.toaddress = ""
				this.num = ""
				this.chainname = "请选择"
			}
		}
	}
</script>
<script module="ether" lang="renderjs">
	export default {
		data() {
			return {
				// 同步过来的初始化数据
				initdata: {},
				// JS注入状态
				jsstatus: false,
				// 数据同步状态
				datastatus: false,
				// 要执行的合约信息
				implementidinfo: "",
				// 要执行的合约ID
				implementid: ""
			}
		},
		mounted() {
			// 动态引入较大类库避免影响页面展示
			let script = document.createElement('script')
			script.src = 'static/script/ethers-5.2.umd.min.js'
			document.head.appendChild(script)
			script.onload = this.changjsstatus
			let script2 = document.createElement('script')
			script2.src = 'static/script/newTronWeb.js'
			document.head.appendChild(script2)
		},
		methods: {
			// js同步
			changjsstatus() {
				this.jsstatus = true
				if (this.datastatus == true) {
					this.getusernum()
				}
			},
			// 同步数据
			getalldata(newValue) {
				if (newValue) {
					this.initdata = newValue
					this.datastatus = true
					if (this.jsstatus == true) {
						this.getusernum()
					}
				}
			},
			// 获取usdt余额
			async getusernum() {
				this.$ownerInstance.callMethod('showloading')
				try {
					if (this.initdata.addressInfo.privateKey) {
						let provider = new ethers.providers.JsonRpcProvider(this.initdata.selectedRpc);
						let signer = new ethers.Wallet(this.initdata.addressInfo.privateKey, provider);
						let address = signer.address
						let tokencontract = new ethers.Contract(this.initdata.config.jumpusdt, this.initdata
							.config.erc20abi, signer);
						let bignum = await tokencontract.balanceOf(address)
						let decimal = await tokencontract.decimals()
						let num = ethers.utils.formatUnits(bignum.toString(), decimal)
						this.$ownerInstance.callMethod('getusernum2', num)
					}
				} catch (e) {
					this.$ownerInstance.callMethod('error', "合约执行失败")
				}
				this.$ownerInstance.callMethod('hideloading')
			},
			// 预执行跨链
			async cross(e) {
				let usernum = e.target.dataset.usernum
				let toaddress = e.target.dataset.toaddress
				let num = e.target.dataset.num
				let min = e.target.dataset.min
				let chainname = e.target.dataset.chainname
				let chainId,to_contract;
				if (chainname == "请选择") {
					return this.$ownerInstance.callMethod('error', "请选择需要跨到的链")
				}
				if (Number(num) <= 0) {
					return this.$ownerInstance.callMethod('error', "请输入跨链数量")
				}
				if (Number(usernum) < Number(num)) {
					return this.$ownerInstance.callMethod('error', "代币数量不足")
				}
				if (Number(min) > Number(num)) {
					return this.$ownerInstance.callMethod('error', "跨链数量少于最小跨链数量")
				}
				if (toaddress == "") {
					return this.$ownerInstance.callMethod('error', "请输入接收地址")
				}
				if (chainname == "TRON") {
					chainId = 0
					to_contract = this.initdata.config.tronusdt
					if (!TronWeb.TronWeb.isAddress(toaddress)) {
						return this.$ownerInstance.callMethod('error', "接收地址格式错误")
					}
				} else if (chainname == "BSC") {
					chainId = 56
					to_contract = this.initdata.config.bscusdt
					if (!ethers.utils.isAddress(toaddress)) {
						return this.$ownerInstance.callMethod('error', "接收地址格式错误")
					}
				}
				this.$ownerInstance.callMethod('showloading')
				try {
					let provider = new ethers.providers.JsonRpcProvider(this.initdata.selectedRpc);
					let signer = new ethers.Wallet(this.initdata.addressInfo.privateKey, provider);
					let address = signer.address
					let tokencontract = new ethers.Contract(this.initdata.config.jumpusdt, this.initdata
						.config.erc20abi,
						signer);
					let allowanceinfo = await tokencontract.allowance(address, this.initdata.config.jumpcross)
					let allowancenum = allowanceinfo.toString()
					if (Number(ethers.utils.parseUnits(num, '18')) > Number(allowancenum)) {
						this.$ownerInstance.callMethod('approveopen')
						this.$ownerInstance.callMethod('hideloading')
						return
					}
					let GasPrice = await provider.getGasPrice()
					let crosscontract = new ethers.Contract(this.initdata.config.jumpcross, this.initdata
						.config
						.crossabi,
						signer);

					let Gaslimit = await crosscontract.estimateGas.exchange(
						this.initdata.config.jumpusdt,
						ethers.utils.parseUnits(num, 18),
						toaddress,
						chainId)

					let data = await crosscontract.populateTransaction.exchange(
						this.initdata.config.jumpusdt,
						ethers.utils.parseUnits(num, 18),
						toaddress,
						chainId, {
							value: ethers.BigNumber.from("0"),
							gasPrice: GasPrice.toString(),
							gasLimit: Gaslimit.toString()

						})
					this.implementidinfo = data
					this.implementid = Date.now()
					let res = {
						from: data.from,
						to: data.to,
						value: ethers.utils.formatUnits(data.value, "ether"),
						data: data.data,
						gasLimit: data.gasLimit.toString(),
						gasPrice: ethers.utils.formatUnits(data.gasPrice, "gwei"),
						fee: ethers.utils.formatUnits(data.gasLimit * data.gasPrice, "ether"),
						id: this.implementid,
						num: num,
						symbol: "USDT",
						methond: "exchange",
						from_chain_id:"5867",
						from_address:data.from,
						from_contract:this.initdata.config.jumpusdt,
						from_amount:num,
						to_chain_id:chainId,
						to_address:toaddress,
						to_contract:to_contract,
						to_amount:num,
					}
					this.$ownerInstance.callMethod('openimplement', res)

				} catch (e) {
					return this.$ownerInstance.callMethod('error', "合约执行失败")
				}
				this.$ownerInstance.callMethod('hideloading')

			},
			// 预授权
			async approve(newValue) {
				if (newValue) {
					this.$ownerInstance.callMethod('showloading')
					try {
						this.$ownerInstance.callMethod('changeapprovestatus', false)
						let provider = new ethers.providers.JsonRpcProvider(this.initdata.selectedRpc);
						let signer = new ethers.Wallet(this.initdata.addressInfo.privateKey, provider);
						let address = signer.address
						let GasPrice = await provider.getGasPrice()
						let tokencontract = new ethers.Contract(this.initdata.config.jumpusdt, this
							.initdata
							.config
							.erc20abi,
							signer);

						let Gaslimit = await tokencontract.estimateGas.approve(
							this.initdata.config.jumpcross,
							this
							.initdata
							.config
							.approvenum)
						let data = await tokencontract.populateTransaction.approve(
							this.initdata.config.jumpcross,
							this.initdata
							.config
							.approvenum, {
								value: ethers.BigNumber.from("0"),
								gasPrice: GasPrice.toString(),
								gasLimit: Gaslimit.toString()
							})

						this.implementidinfo = data
						this.implementid = Date.now()
						let res = {
							from: data.from,
							to: data.to,
							value: ethers.utils.formatUnits(data.value, "ether"),
							data: data.data,
							gasLimit: data.gasLimit.toString(),
							gasPrice: ethers.utils.formatUnits(data.gasPrice, "gwei"),
							fee: ethers.utils.formatUnits(data.gasLimit * data.gasPrice, "ether"),
							id: this.implementid,
							symbol: "USDT",
							methond: "approve"
						}
						this.$ownerInstance.callMethod('openimplement', res)

					} catch (e) {
						this.$ownerInstance.callMethod('error', "合约执行失败")
					}
					this.$ownerInstance.callMethod('hideloading')
				}

			},
			// 去执行
			async implement(newValue) {
				if (newValue && newValue == this.implementid) {
					this.$ownerInstance.callMethod('showloading')
					try {
						let provider = new ethers.providers.JsonRpcProvider(this.initdata.selectedRpc);
						let signer = new ethers.Wallet(this.initdata.addressInfo.privateKey, provider);
						let res = await signer.sendTransaction(this.implementidinfo)
						let calldata = await provider.waitForTransaction(res.hash);
						if (calldata.status == 1) {
							this.$ownerInstance.callMethod("error", '合约请求成功')
						}
						this.getusernum()
						this.$ownerInstance.callMethod("addCrossLog", res.hash)
						this.$ownerInstance.callMethod('implementover')
					} catch (e) {
						this.$ownerInstance.callMethod('error', "合约执行失败")
					}
					this.$ownerInstance.callMethod('hideloading')
				}
			}
		}
	}
</script>
<style lang="less" scoped>
	.page {
		width: 100vw;
		height: 100vh;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		background-color: #F7F7F7;

		.hecswap {
			padding-top: 26upx;
			height: 100%;
			overflow-y: scroll;
			padding-bottom: 100upx;
			box-sizing: border-box;

			.block1 {
				width: 702upx;
				background-color: #fff;
				border-radius: 32upx;
				padding: 24upx 24upx;
				box-sizing: border-box;
				margin: 0upx auto;

				.line1 {
					display: flex;
					justify-content: space-between;
					align-items: center;

					.left {
						font-size: 28upx;
						color: #666666;
					}

					.right {
						display: flex;
						align-items: center;

						.image {
							width: 48upx;
						}

						.text {
							font-size: 28upx;
							color: #666666;
						}
					}
				}

				.line2 {
					width: 654upx;
					height: 140upx;
					background-color: #F7F7F7;
					border-radius: 24upx;
					box-sizing: border-box;
					padding: 26upx 24upx;
					margin-top: 16upx;
					display: flex;
					align-items: center;

					.left {
						display: flex;
						align-items: center;

						.tokenicon {
							width: 72upx;
						}

						.texts {
							.text1 {
								font-size: 36upx;
								color: #333333;
							}

							.text2 {
								font-size: 24upx;
								color: #999999;
								margin-top: 4upx;
							}

							margin-left:24upx;
						}
					}

					.right {
						margin-left: 105upx;

						.numinput {
							height: 64upx;
							background: #fff;
						}
					}
				}

				.line3 {

					.image {
						display: block;
						margin: 0px auto;
						width: 64upx;
						margin-top: 24upx;
					}
				}

				.line4 {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-top: 16upx;
					margin-bottom: 16upx;

					.left {
						font-size: 28upx;
						color: #666666;
					}

					.right {
						display: flex;
						align-items: center;

						.image {
							width: 48upx;
						}

						.text {
							font-size: 28upx;
							color: #666666;
						}

					}
				}

				.line5 {
					width: 654upx;
					height: 140upx;
					background-color: #F7F7F7;
					border-radius: 24upx;
					box-sizing: border-box;
					padding: 26upx 24upx;
					// margin-top: 16upx;
					display: flex;
					align-items: center;
					justify-content: space-between;

					.left {
						display: flex;
						align-items: center;

						.image {
							width: 80upx;
						}

						.text {
							margin-left: 20upx;
						}
					}

					.center {
						.image {
							width: 50upx;
						}
					}

					.right {
						display: flex;
						align-items: center;

						.image {
							width: 80upx;
						}

						.text {
							margin-left: 20upx;
						}
					}
				}

				.toaddress {
					width: 654upx;
					background-color: #F7F7F7;
					// height:88upx;
					border-radius: 24upx;
					box-sizing: border-box;
					margin-top: 16upx;

					.toaddressinput {
						height: 56upx;
						font-size: 32upx;
					}
				}

				.line6 {
					width: 100%;
					box-sizing: border-box;
					display: flex;
					justify-content: space-between;
					margin-top: 24upx;

					.button {
						width: 100%;
						line-height: 92upx;
						text-align: center;

						color: #fff;
						border-radius: 16upx;
					}

					.button1 {
						background-color: #FFBC42;
					}

					.button2 {
						background-color: #03BAE8;
					}
				}

				.line7box {
					display: flex;
					align-items: center;
					justify-content: space-between;

					.line7 {
						width: 100%;
						line-height: 92upx;
						background-color: #FF760F;
						color: #fff;
						text-align: center;
						border-radius: 16upx;
						margin-top: 24upx;
					}

					.line7:nth-child(2) {
						background-color: #03BAE8;
					}
				}
			}

			.block2 {
				width: 702upx;
				// height:328upx;
				margin: 0upx auto;
				background-color: #fff;
				padding: 6upx 32upx;
				box-sizing: border-box;
				margin-top: 32upx;
				border-radius: 32upx;
				padding-bottom: 30upx;

				.line {
					display: flex;
					justify-content: space-between;
					margin-top: 36upx;

					.left {
						color: #888888;
						font-size: 32upx;
					}

					.right {
						color: #333333;
					}
				}
			}

			.logBox {
				width: 702upx;
				margin: 0 auto;
				padding-bottom: 130upx;

				.title {
					display: flex;
					justify-content: space-between;
					font-size: 32upx;
					color: #131313;
					margin: 28px 0 20upx;

					.more {
						color: #A2A2A2;
						font-size: 28upx;
					}
				}
			}

		}

		.block3 {
			height: 600upx;
			background-color: #fff;
			border-radius: 20upx 20upx 0upx 0upx;

			.line1 {
				text-align: center;
				position: relative;
				padding-top: 32upx;
				padding-bottom: 30upx;

				.text1 {
					font-size: 36upx;
					color: #333333;
				}

				.icon1 {
					width: 48upx;
					height: 48upx;
					position: absolute;
					right: 32upx;
					top: 32upx;
					border-radius: 50%;
					background-color: #EEEEEE;
					text-align: center;
					line-height: 48upx;
				}
			}

			.line2box {
				.line2 {
					display: flex;
					justify-content: space-between;
					padding: 0upx 32upx;
					align-items: center;
					margin-top: 24upx;

					.left {
						display: flex;
						justify-content: space-between;
						align-items: center;

						.image1 {
							width: 72upx;
						}

						.text1 {
							font-size: 32upx;
							color: #4B3E58;
							margin-left: 16upx;
						}
					}

					.right {
						font-size: 40upx;
						color: #4B3E58;
					}
				}
			}

			.line3 {
				width: 686upx;
				line-height: 88upx;
				text-align: center;
				font-size: 28upx;
				color: #fff;
				background: #26CF6D;
				margin: 0px auto;
				margin-top: 40upx;
				border-radius: 18upx;
				margin-top: 44upx;

			}
		}

		.block4 {
			width: 686upx;
			padding: 32upx 56upx;
			border-radius: 48upx;
			box-sizing: border-box;
			background-color: #fff;

			.title {
				font-size: 48upx;
				color: #333333;
				text-align: center;
				border-bottom: 2upx solid #F7F7F7;
				padding-bottom: 32upx;
			}

			.line1 {
				font-size: 28upx;
				color: #545454;
				margin-top: 32upx;
			}

			.line2 {
				margin-top: 16upx;
				height: 96upx;

				.input {
					height: 96upx;
					width: 100%;


				}
			}

			.line3 {
				font-size: 24upx;
				color: #C2C2C2;
				margin-top: 16upx;

				.tip {
					color: red;
				}
			}

			.line4 {
				width: 100%;
				display: flex;
				justify-content: space-between;

				.button {
					width: 271upx;
					height: 92upx;
					line-height: 92upx;
					border-radius: 64upx;
					text-align: center;
					color: #fff;
					margin-top: 48upx;
				}

				.button1 {
					background-color: #03BAE8;
				}

				.button2 {
					background-color: #FF760F;
				}
			}

		}
	}

	/deep/ .uni-easyinput__content {
		height: 100%;
		background-color: #F7F7F7 !important;
	}

	/deep/ .uni-easyinput__content-input {
		font-size: 24rpx; // 设置字体大小    
	}
</style>